package com.iwords.android;

import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;

import android.app.ListActivity;
import android.content.Context;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class WordsList  extends ListActivity implements OnInitListener {
	
	List<WordStatus> words = WordsQueueManager.getInstance().getCurrentQueue();
	MediaPlayer mediaPlayer;
	
	private class EfficientAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        public EfficientAdapter(Context context) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);
        }

        /**
         * The number of items in the list is determined by the number of speeches
         * in our array.
         *
         * @see android.widget.ListAdapter#getCount()
         */
        public int getCount() {
            return words.size();
        }

        /**
         * Since the data comes from an array, just returning the index is
         * sufficent to get at the data. If we were using a more complex data
         * structure, we would return whatever object represents one row in the
         * list.
         *
         * @see android.widget.ListAdapter#getItem(int)
         */
        public Object getItem(int position) {
            return words.get(position);
        }

        /**
         * Use the array index as a unique id.
         *
         * @see android.widget.ListAdapter#getItemId(int)
         */
        public long getItemId(int position) {
            return position;
        }

        /**
         * Make a view to hold each row.
         *
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid unneccessary calls
            // to findViewById() on each row.
            ViewHolder holder;

            // When convertView is not null, we can reuse it directly, there is no need
            // to reinflate it. We only inflate a new View when the convertView supplied
            // by ListView is null.
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.words_list_item, null);

                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new ViewHolder();
        		Typeface font = Typeface.createFromAsset(WordsList.this.getAssets(), "SEGOEUI.TTF");
                holder.spelling = (TextView) convertView.findViewById(R.id.auto_reading_spelling);
                holder.phonetics = (TextView) convertView.findViewById(R.id.auto_reading_phonetics);
                holder.meaning = (TextView) convertView.findViewById(R.id.auto_reading_meaning);
        		holder.phonetics.setTypeface(font);

                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (ViewHolder) convertView.getTag();
            }

            // Bind the data efficiently with the holder.
            WordStatus word = words.get(position);
            String spelling = word.getSpelling() + " ";
			String phonetics = (word.getPhonetics()==null?"":word.getPhonetics());
			String meaning = word.getMeaning();
			holder.spelling.setText(StringEscapeUtils.unescapeHtml(spelling));
			holder.phonetics.setText(StringEscapeUtils.unescapeHtml(phonetics));
			holder.meaning.setText(meaning);
            return convertView;
        }

        class ViewHolder {
            TextView spelling;
            TextView phonetics;
            TextView meaning;
        }
    }


    public void close(View view) {
       this.vibrate();
	   this.finish();
	   if(mediaPlayer != null){
		   mediaPlayer.stop();
	   }
    }
    
	private void vibrate(){
		Vibrator mVibrator = (Vibrator)getApplication().getSystemService(android.app.Service.VIBRATOR_SERVICE);
		mVibrator.vibrate(new long[]{50,50},-1);
	}
	private void play(WordStatus word){
		try{
			if(word==null) return;
			//System.out.println(".........................AutoReading.play() word = "+word.getSpelling());
			String spelling = word.getSpelling();
			String href = this.getResources().getString(R.string.voice);
			href += spelling.substring(0,1).toLowerCase() + "/" + CodeUtils.encode(spelling) +".wav";
			//System.out.println(".........................AutoReading.play() href = "+href);
			try{
				mediaPlayer.setDataSource(href);
				mediaPlayer.prepare();
				mediaPlayer.start();
			}catch(Exception e){
				mediaPlayer.reset();
				//e.printStackTrace();
			}
		}catch(Exception e){
			e.printStackTrace();
		}		
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.words_list);
		//System.out.println("...........................AutoReading.onCreate() ");
		//System.out.println("words.size() = "+words.size());
		if(words.size() < 1){
			displayMessage("当前选择的队列，没有可供朗读的单词。");
			return;
		}
		
        setListAdapter(new EfficientAdapter(this));
        final ListView listView = getListView();
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        //为ListView设置列表项点击监听器
        listView.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                    	//System.out.println("AutoReading. 列表选择。");
                    	WordsList.this.play(words.get(position));
                    }
        });

	}
	
	@Override
	protected void onStart() {
		super.onStart();
		//System.out.println("...........................AutoReading.onStart() ");
		this.mediaPlayer = new MediaPlayer();
	}
	
	@Override protected void onDestroy () {
		if(this.mediaPlayer != null){
			this.mediaPlayer.release();
		}
		//System.out.println("...........................AutoReading.onDestroy() this.mediaPlayer.release();");
		super.onDestroy();
	}

	@Override
	public void onInit(int arg0) {
		//System.out.println("...........................AutoReading.onInit()");
	}
	private void displayMessage(String message){
		Toast t1 = Toast.makeText(getApplication(), message, Toast.LENGTH_LONG*2);
		t1.show();
	}
}